import browser from "webextension-polyfill";
import { ElMessage } from 'element-plus'
import { SD_SYSTEM } from "@src/globalData/enum";
import { getSportMarketHeaders, getSportMarketZcqHeaders, getStorageUserinfo, getTabMark } from "@src/entries/background/utils/common";
import { sendMessageGetHeadersToTab, sendMessageGetUserInfo, sendMessageGetZcqHeadersToTab } from "@src/entries/background/tabs";
import { userUnitid } from "@src/config/accountInfo";
import dayjs from "dayjs";

const appEnv = import.meta.env.VITE_APP_ENV

/** 生产环境不能手动获取数据的时间 */
const prodUnableTimes = [[0,2],[15,17],[30,32],[45,47]]
/** 测试环境不能手动获取数据的时间 */
// const devUnableTimes = [[7,9],[22,24],[37,39],[52,54]]
const devUnableTimes:any[] = []

/** 校验不能手动获取数据的时间 */
export const validateTimeMinute = () => {
  const cMinute = dayjs().minute()
  const unableTimes = appEnv === 'development' ? devUnableTimes : prodUnableTimes
  if(!devUnableTimes.length) return true
  if(unableTimes.some((val) => cMinute >= val[0] && cMinute <= val[1])) {
    const tip = '请勿在以下时刻获取数据：' + unableTimes.map(item => `hh:${String(item[0]).padStart(2, '0')} ~ hh:${String(item[1]).padStart(2, '0')}、`).join(' ')
    ElMessage.error(tip)
    return false
  }
  return true
}

/** 现货市场 请求数据 */
const getStorageReqInfo = async (onlyHeaders = false, systemMainTab:any[] = [], systemSpotMarketTab:any[] = []) => {
  try {
    const headers = await getSportMarketHeaders()
    const userInfo = await getStorageUserinfo()
    const unitid = userUnitid?.[userInfo?.userName] || ''
    
    const reqStorageInfo:{headers:HeadersInit, unitid:string} = {headers, unitid}

    if(onlyHeaders && reqStorageInfo.headers) return Promise.resolve(reqStorageInfo)
    if(reqStorageInfo.headers && reqStorageInfo.unitid) return Promise.resolve(reqStorageInfo)

    if(systemMainTab.length !== 1) ElMessage.error('请打开主系统且只打开一个对应的tab')
    if(systemSpotMarketTab.length !== 1) ElMessage.error('请打开子系统且只打开一个对应的tab：现货市场')
    return Promise.reject(new Error('no reqInfo'))
  } catch(e) {
    console.error(e)
    return Promise.reject(e)
  }
}

/** 获取 手动获取数据时需要的信息 */
export const getSpotMartetReqInfo = async (onlyHeaders = false) => {
  let [systemMainTab, systemSpotMarketTab]:browser.Tabs.Tab[][] = [[],[]]
  try {
    const tabs = await browser.tabs.query({})

    systemMainTab = tabs.filter((tab) => {
      const tabMark = getTabMark(new URL(tab.url || ''))
      return decodeURIComponent(tabMark) === decodeURIComponent(SD_SYSTEM.MAIN)
    }) as browser.Tabs.Tab[]

    if(systemMainTab.length !== 1) {
      const reqStorageInfo = await getStorageReqInfo(onlyHeaders, systemMainTab)
      return Promise.resolve(reqStorageInfo)
    }
      

    systemSpotMarketTab = tabs.filter((tab) => {
      const tabMark = getTabMark(new URL(tab.url || ''))
      return decodeURIComponent(tabMark) === decodeURIComponent(SD_SYSTEM.SPOT_MARKET)
    }) as browser.Tabs.Tab[]

    if(systemSpotMarketTab.length !== 1) {
      const reqStorageInfo = await getStorageReqInfo(onlyHeaders, systemMainTab, systemSpotMarketTab)
      return Promise.resolve(reqStorageInfo)
    } 

    const mark = getTabMark(new URL(systemSpotMarketTab[0].url || ''))
    const headers = await sendMessageGetHeadersToTab(systemSpotMarketTab[0], mark)

    if(onlyHeaders) return Promise.resolve({headers, unitid:''})

    const userInfo = await sendMessageGetUserInfo(SD_SYSTEM.MAIN)
    let unitid = userUnitid?.[userInfo?.userName] || ''

    if(!unitid) {
      const theMsg = ElMessage.error({
        message: '此账号未配置 unitid, 请打开 【现货市场】-【现货交易】-【日前交易结果】-【一次日前交易结果查询】',
        duration: 0
      })
      unitid = await sendMessageGetUserInfo(SD_SYSTEM.SPOT_MARKET)
      theMsg.close()
    }

    return Promise.resolve({headers,unitid})
  }catch(e) {
    console.error(e)
    console.error(new Error('getSpotMartetReqInfo error'))

    const reqStorageInfo = await getStorageReqInfo(onlyHeaders, systemMainTab, systemSpotMarketTab)
    return Promise.resolve(reqStorageInfo)
    
    // const headers = await getSportMarketHeaders()
    // const userInfo = await getStorageUserinfo()
    // const unitid = userUnitid?.[userInfo?.userName] || ''
    
    // const reqStorageInfo:{headers:HeadersInit, unitid:string} = {headers, unitid}

    // if(onlyHeaders && reqStorageInfo.headers) return Promise.resolve(reqStorageInfo)
    // if(reqStorageInfo.headers && reqStorageInfo.unitid) return Promise.resolve(reqStorageInfo)

    // if(systemMainTab.length !== 1) ElMessage.error('请打开主系统且只打开一个对应的tab')
    // if(systemSpotMarketTab.length !== 1) ElMessage.error('请打开子系统且只打开一个对应的tab：现货市场')

    return Promise.reject(e)
  }
}

/** 现货市场中长期 请求数据 */
const getStorageZcqReqInfo = async (systemMainTab:any[] = [], systemSpotMarketZcqTab:any[] = []) => {
  try {
    const headers = await getSportMarketZcqHeaders()
    const userInfo = await getStorageUserinfo()

    const unitid = userInfo?.memberId
    
    const reqStorageInfo:{headers:HeadersInit, unitid:string} = {headers, unitid}

    if(reqStorageInfo.headers && reqStorageInfo.unitid) return Promise.resolve(reqStorageInfo)

    if(systemMainTab.length !== 1) ElMessage.error('请打开主系统且只打开一个对应的tab')
    if(systemSpotMarketZcqTab.length !== 1) ElMessage.error('请打开子系统且只打开一个对应的tab：现货市场中长期')
    return Promise.reject(new Error('no reqInfo'))
  } catch(e) {
    console.error(e)
    return Promise.reject(e)
  }
}

/** 获取 手动获取中长期系统数据时需要的信息 */
export const getSpotMartetZcqReqInfo = async () => {
  let [systemMainTab, systemSpotMarketZcqTab]:browser.Tabs.Tab[][] = [[],[]]
  try {
    const tabs = await browser.tabs.query({})

    systemMainTab = tabs.filter((tab) => {
      const tabMark = getTabMark(new URL(tab.url || ''))
      return decodeURIComponent(tabMark) === decodeURIComponent(SD_SYSTEM.MAIN)
    }) as browser.Tabs.Tab[]

    if(systemMainTab.length !== 1) {
      const reqStorageInfo = await getStorageZcqReqInfo(systemMainTab)
      return Promise.resolve(reqStorageInfo)
    } 
      

    systemSpotMarketZcqTab = tabs.filter((tab) => {
      const tabMark = getTabMark(new URL(tab.url || ''))
      return decodeURIComponent(tabMark) === decodeURIComponent(SD_SYSTEM.SPOT_MARKET_ZCQ)
    }) as browser.Tabs.Tab[]

    if(systemSpotMarketZcqTab.length !== 1) {
      const reqStorageInfo = await getStorageZcqReqInfo(systemMainTab, systemSpotMarketZcqTab)
      return Promise.resolve(reqStorageInfo)
    } 

    const mark = getTabMark(new URL(systemSpotMarketZcqTab[0].url || ''))
    const headers = await sendMessageGetZcqHeadersToTab(systemSpotMarketZcqTab[0], mark)

    const userInfo = await sendMessageGetUserInfo(SD_SYSTEM.MAIN)

    // const headers = await sendMessageGetZcqHeadersToTab(tab, mark)
    // const userInfo = await sendMessageGetUserInfo(SD_SYSTEM.MAIN)

    const unitid = userInfo?.memberId

    return Promise.resolve({headers,unitid})
  }catch(e) {
    console.error(e)
    console.error(new Error('getSpotMartetReqInfo error'))

    const reqStorageInfo = await getStorageZcqReqInfo(systemMainTab, systemSpotMarketZcqTab)
    return Promise.resolve(reqStorageInfo)
    
    // const headers = await getSportMarketHeaders()
    // const userInfo = await getStorageUserinfo()
    // const unitid = userUnitid?.[userInfo?.userName] || ''
    
    // const reqStorageInfo:{headers:HeadersInit, unitid:string} = {headers, unitid}

    // if(onlyHeaders && reqStorageInfo.headers) return Promise.resolve(reqStorageInfo)
    // if(reqStorageInfo.headers && reqStorageInfo.unitid) return Promise.resolve(reqStorageInfo)

    // if(systemMainTab.length !== 1) ElMessage.error('请打开主系统且只打开一个对应的tab')
    // if(systemSpotMarketTab.length !== 1) ElMessage.error('请打开子系统且只打开一个对应的tab：现货市场')

    return Promise.reject(e)
  }
}

/**
 * 返回开始到结束的每一天的日期 数组
 * @method betweenStartEndDays
 * @param {String} start
 * @param {String} end
 * @param {String} format
 * @returns {Array}
 */
export const betweenStartEndDays = (start:string, end:string, format = 'YYYY-MM-DD') => {
  const betweenDayNum = dayjs(end).diff(dayjs(start), 'day') + 1
  const betweenDays = []
  for (let i = 0; i < betweenDayNum; i++) {
    betweenDays.push(dayjs(start).add(i, 'day').format(format))
  }
  return betweenDays
}

/** 停止自动获取数据 */
export const stopAutoGetdata = async () => {
  // stopBackgroundAutoGetdata
  console.log('stopAutoGetdata')
  try {
    const backMsg = await browser.runtime.sendMessage({message:'stopBackgroundAutoGetdata'})
    console.log('stopAutoGetdata backMsg', backMsg)
  }catch(e) {
    console.error(e)
  }
}

/** 开始自动获取数据 */
export const startAutoGetdata = async (auto = false) => {
  // startBackgroundAutoGetdata
  console.log('startAutoGetdata')
  if(!auto && import.meta.env.VITE_APP_GETDATA_WAY !== 'auto') {
    console.error(`${import.meta.env.VITE_APP_GETDATA_WAY} 打包环境不能自动启动 自动获取现货市场系统的数据`)
    return
  }
  try {
    const {headers, unitid} = await getSpotMartetReqInfo(false)
    const backMsg = await browser.runtime.sendMessage({message:'startBackgroundAutoGetdata', headers, unitid})
    console.log('startAutoGetdata backMsg', backMsg)
  }catch(e) {
    console.error(e)
  }
}
